<template>
  <div class="users">
    <div class="users_header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card shadow="hover" class="users_con">
      <!-- 搜索框 -->
      <div class="users_sea">
        <el-input placeholder="请输入用户名" clearable @clear="getuserlist" v-model="queryinfo.query">
          <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
        </el-input>
        <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
      </div>
      <!-- 列表 -->
      <el-table :data="userlist" style="width: 100%">
        <el-table-column label="#" width="60" type="index">
        </el-table-column>
        <el-table-column label="姓名" width="220">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="220">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电话" width="220">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="200">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.role_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="150">
          <!-- eslint-disable-next-line -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"
              active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button size="mini" type="info" @click="handlejiao(scope.$index, scope.row)">角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block paging">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryinfo.pagenum" :page-sizes="[5,8,15]" :page-size="queryinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <!-- 添加框 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible" :before-close="handleClose" center
        @close="addcancel">
        <el-form :model="form" :rules="AddRules" ref="reference">
          <el-form-item label="姓名" :label-width="form.formLabelWidth" prop="username">
            <el-input v-model="form.username" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="form.formLabelWidth" prop="password">
            <el-input v-model="form.password" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="form.formLabelWidth" prop="email">
            <el-input v-model="form.email" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="form.formLabelWidth" prop="mobile">
            <el-input v-model="form.mobile" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDeter">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改框 -->
      <el-dialog title="修改信息" :visible.sync="dialogGaiVisible" :before-close="handleClose" center
        @close="changecancel">
        <el-form :model="changeform" :rules="changeRules" ref="refchange">
          <el-form-item label="用户名" :label-width="form.formLabelWidth">
            <el-input v-model="changeform.username" autocomplete="off" clearable :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="form.formLabelWidth" prop="email">
            <el-input v-model="changeform.email" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="form.formLabelWidth" prop="mobile">
            <el-input v-model="changeform.mobile" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogGaiVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeDeter">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 权限框 -->
      <el-dialog title="分配权限" :visible.sync="dialogLevelVisible" :before-close="handleClose"
        @close="levelcancel">
        <p>当前的用户：<el-tag>{{levelID.username}}</el-tag>
        </p>
        <p>当前的角色：<el-tag type="warning">{{levelID.role_name}}</el-tag>
        </p>
        <p>分配新角色：
          <el-select v-model="roleValue" placeholder="请选择" :clearable='true'>
            <el-option v-for="item in levelList" :key="item.id" :label="item.roleName"
              :value="item.id" ref="reflevel">
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogLevelVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmLevel">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UsErs',
  data() {
    return {
      // 获取用户列表的参数
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      userlist: [],
      total: 0,
      // 添加框的显示
      dialogFormVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        formLabelWidth: '200px',
      },
      // 添加框的表单验证效果
      AddRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 15, max: 20, message: '长度在 15 到 20 个字符', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度11个数字', trigger: 'blur' },
        ],
      },
      // 修改框的显示
      dialogGaiVisible: false,
      changeform: {
        username: '',
        id: 0,
        email: '',
        mobile: '',
      },
      // 修改框的表单验证
      changeRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 15, max: 20, message: '长度在 15 到 20 个字符', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11的数字', trigger: 'blur' },
        ],
      },
      // 权限框的显示
      dialogLevelVisible: false,
      // 权限框需要的用户ID
      levelID: '',
      // 权限框需要的角色列表
      levelList: [],
      // 分配权限下拉框
      roleValue: '',
    }
  },
  methods: {
    // 获取用户数据列表
    async getuserlist() {
      const { data: res } = await this.$http.get('users', { params: this.queryinfo })
      // console.log(res)
      this.total = res.data.total
      this.userlist = res.data.users
    },
    // 改变当前页条数事件
    handleSizeChange(val) {
      this.queryinfo.pagesize = val
      this.getuserlist()
    },
    // 改变当前页数事件
    handleCurrentChange(val) {
      this.queryinfo.pagenum = val
      this.getuserlist()
    },
    // 状态开关
    async stateChange(user) {
      const { data: userState } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      // console.log(userState)
      // console.log(user)
      if (userState.meta.status != 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 确认关闭添加框、修改框
    handleClose(done) {
      this.$confirm('确认关闭?填写数据将不被保存')
        .then(() => {
          done()
        })
        .catch(() => {})
    },
    // 关闭添加框
    addcancel() {
      this.$refs.reference.resetFields()
    },
    // 确认添加
    addDeter() {
      this.$refs.reference.validate(async (e) => {
        if (!e) {
          this.$message.error('抱歉，填写内容不符合格式')
          return
        }
        this.dialogFormVisible = false
        const { data: addRes } = await this.$http.post('users', this.form)
        if (addRes.meta.status != 201) {
          return this.$message.error('创建失败')
        }
        this.$message.success('创建成功')
        this.getuserlist()
      })
    },
    // 关闭修改框
    changecancel() {
      this.$refs.refchange.resetFields()
    },
    // 点击编辑
    handleEdit(a, b) {
      this.dialogGaiVisible = true
      this.changeform.username = b.username
      this.changeform.id = b.id
    },
    // 确认修改
    changeDeter() {
      this.$refs.refchange.validate(async (e) => {
        if (!e) {
          this.$message.error('抱歉，填写内容不符合格式')
          return
        }
        this.dialogGaiVisible = false
        const { data: changeRes } = await this.$http.put(`users/${this.changeform.id}`, {
          email: this.changeform.email,
          mobile: this.changeform.mobile,
        })
        if (changeRes.meta.status != 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getuserlist()
      })
    },
    // 删除用户数据
    handleDelete(a, b) {
      this.$confirm('此操作将永久删除此条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: del } = await this.$http.delete(`users/${b.id}`)
          if (del.meta.status != 200) {
            this.$message.error('删除失败')
            return
          }
          this.$message.success('删除成功')
          if (this.userlist.length == 1) {
            this.queryinfo.pagenum--
          }
          this.getuserlist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 点击分配角色
    async handlejiao(a, b) {
      this.dialogLevelVisible = true
      this.levelID = b
      const { data: levelres } = await this.$http.get('roles')
      this.levelList = levelres.data
      // console.log(levelres.data)
    },
    // 关闭分配角色框
    levelcancel() {
      this.roleValue = ''
    },
    // 分配权限框点确认
    async confirmLevel() {
      if (this.roleValue == '') {
        this.$message.error('未选择新角色！')
        return
      }
      const { data: roles } = await this.$http.put(`users/${this.levelID.id}/role`, {
        rid: this.roleValue,
      })
      if (roles.meta.status != 200) {
        this.$message.error('分配失败')
        return
      }
      console.log(roles)
      this.$message.success('分配成功')
      this.getuserlist()
      this.dialogLevelVisible = false
    },
  },
  // 打开页面即开始加载用户数据
  created() {
    this.getuserlist()
  },
}
</script>

<style lang='less' scoped>
.users {
  height: 100%;
}
.users_header {
  .el-breadcrumb {
    font-size: 17px;
  }
}
.users_con {
  margin-top: 30px;
  height: 90%;
  background: #fff;
  padding: 20px;
}
.users_sea {
  width: 560px;
  display: flex;
  justify-content: space-between;
  .el-input {
    width: 80%;
  }
}
.el-table {
  margin-top: 20px;
}
.paging {
  margin-top: 20px;
}
.el-dialog {
  .el-input {
    width: 360px;
    margin-left: 50px;
  }
  p {
    margin-bottom: 15px;
  }
}
</style>